package org.demo.flypig;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

import org.apache.commons.io.IOUtils;
import org.demo.flypig.orm.HibernateUtil;
import org.demo.flypig.orm.SocialItem;
import org.h2.tools.Server;
import org.hibernate.Session;
import org.hibernate.Transaction;

import weibo4j.Paging;
import weibo4j.Status;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

public class FlyPig {
	
	private static final Scanner scanner = new Scanner(System.in);
	
	private static final String PROPERTY_FILE_NAME = "weibo.properties";
	private static final String LABEL_ACCESS_TOKEN = "access-token";
	private static final String LABEL_TOKEN_SECRET = "token-secret";
	private static final String LABEL_CALLBACK_URL = "callback-url";
	
	private static Session session;

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws WeiboException 
	 */
	public static void main(String[] args) throws Exception {
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			Properties prop = loadProperties();
			executeAction(prop);
			println("Bye!");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
			
			HibernateUtil.shutdown();
		}
	}

	private static Properties loadProperties() {
		Properties prop = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(PROPERTY_FILE_NAME);
			prop.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
		return prop;
	}

	private static void executeAction(Properties prop) throws WeiboException {
		String action = showCommand();
		
		while (!action.equalsIgnoreCase("e")) {
			Weibo weibo = createClient(prop);
			if (action.equals("c")) {
				RequestToken requestToken = weibo.getOAuthRequestToken(prop.getProperty(LABEL_CALLBACK_URL));
				String authorizeUrl = requestToken.getAuthorizationURL();
				println("Pleae open your browser & access below link:");
				println(authorizeUrl);
				println("After pass the authentication, input the string showing in your browser:");
				println("Verifier:");
				String verifier = scanner.nextLine();
				AccessToken accessToken = requestToken.getAccessToken(verifier);
				prop.setProperty(LABEL_ACCESS_TOKEN, accessToken.getToken());
				prop.setProperty(LABEL_TOKEN_SECRET, accessToken.getTokenSecret());
				
				FileOutputStream out = null;
				try {
					out = new FileOutputStream(PROPERTY_FILE_NAME);
					prop.store(out, "Update " + PROPERTY_FILE_NAME + "with Key '" + LABEL_ACCESS_TOKEN + "' & Value '" + accessToken + "'");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					IOUtils.closeQuietly(out);
				}
			} else if (action.equals("l")) {
				weibo.setOAuthAccessToken(prop.getProperty(LABEL_ACCESS_TOKEN), prop.getProperty(LABEL_TOKEN_SECRET));
				println("Enter a topic you like:");
				String topic = scanner.nextLine();
				List<Status> statusOfTopic = weibo.getTrendStatus(topic, new Paging());
				Transaction tx = session.beginTransaction();
				for (Status status : statusOfTopic) {
					println(status.toString());
					SocialItem item = new SocialItem();
					item.setGuid(status.getId() + "");
					item.setMessage(status.getText());
					session.save(item);
				}
				tx.commit();
			} else {
				println("'" + action + "' is not a valid action");
			}
			
			action = showCommand();
		}
	}
	
	private static void println(String msg) {
		System.out.println(msg);
	}
	
	private static String showCommand() {
		println("Select your action:");
		println("[c]reate a new Access Token");
		println("[l]oad exsiting AccessToken");
		println("[e]xit");
		return scanner.nextLine();
	}

	
	private static Weibo createClient(Properties property) {
		Weibo weibo = new Weibo();
		weibo.setOAuthConsumer(property.getProperty("app-key"), property.getProperty("app-secret"));
		return weibo;
	}
}
